<template>
    <van-popup v-model:show="show" round position="bottom" :style="{ height: '60%' }">
        <div class="add-wrap">
            <header class="header">
                <span class="close" @click="show = false">
                    <van-icon name="cross"></van-icon>
                </span>
                <van-button class="add-btn" type="primary" size="small" @click="addBill">确定</van-button>
            </header>

            <div class="filter">
                <div class="type">
                    <span @click="changeType('expense')" :class="{expense:true,active:payType == 'expense'}">支出</span>
                    <span @click="changeType('income')" :class="{income:true,active:payType == 'income'}">收入</span>
                </div>
                <div class="time" @click="showDay = true">
                    {{$filters.transDay(date)}}
                    <i class="iconfont icon-sort-down"></i>
                </div>
            </div>


            <div class="money">
                <span class="sufix">￥</span>
                <span class="amount animation">{{amount}}</span>
            </div>

            <div class="type-wrap">
                <div class="type-body" v-if="payType == 'expense'">
                    <div class="type-item" v-for="item in expense" :key="item.id" @click="choseType(item)">
                        <span :class="{'iconfont-wrap':true,'expense':true,active:currentType.id == item.id}">
                            <i class="iconfont" :class="typeMap[item.id].icon"></i>
                        </span>
                        <span>
                            {{item.name}}
                        </span>
                    </div>
                </div>
                <div class="type-body" v-else>
                    <div class="type-item" v-for="item in income" :key="item.id" @click="choseType(item)">
                        <span :class="{'iconfont-wrap':true,'income':true,active:currentType.id == item.id}">
                            <i class="iconfont" :class="typeMap[item.id].icon"></i>
                        </span>
                        <span>
                            {{item.name}}
                        </span>
                    </div>
                </div>
            </div>

            <div class="remark" v-if="remark" @click="remarkVisible = true">
                {{remark}}
            </div>
            <div class="remark" v-else @click="remarkVisible = true">
                添加备注
            </div>
            <van-dialog v-model:show="remarkVisible" title="备注" show-cancel-button>
                <van-field v-model="remark" placeholder="请输入备注" rows="2" autosize type="textarea" maxlength="10"
                    show-word-limit />
            </van-dialog>

            <van-number-keyboard :show="true" extra-key="." @input="inputChange" @delete="remove" />
        </div>
        <van-popup v-model:show="showDay" round position="bottom" :style="{ height: '45%' }">
            <van-datetime-picker v-model="date" type="date" title="选择年月日" @confirm="choseDay"
                @cancel="showDay = false" />
        </van-popup>
    </van-popup>
</template>

<script>

import { typeMap } from '../utils'
import axios from '../utils/axios';
import { onMounted, reactive, toRefs, withCtx } from 'vue';
import { Toast } from 'vant';
import dayjs from 'dayjs';

export default {
    props: {
        refresh: Function,
        detail: {
            type: Object,
            default: {}
        }
    },
    setup(props, ctx) {
        console.log(props.detail);
        const id = props.detail.id;
        const state = reactive({
            show: false,
            showDay: false,
            payType: id ? (props.detail.pay_type == 1 ? 'expense' : 'income') : 'expense',
            date: id ? dayjs(Number(props.detail.date)).$d : new Date(),
            amount: id ? props.detail.amount : '',
            expense: [],
            income: [],
            typeMap: typeMap,
            currentType: id ? { id: props.detail.type_id, name: props.detail.type_name } : {},
            remarkVisible: false,
            remark: id ? props.detail.remark : '',

        })

        onMounted(async () => {
            const { data: { list } } = await axios.get('/type/list')
            console.log(list);
            state.expense = list.filter(i => i.type == 1)
            state.income = list.filter(i => i.type == 2)
            if (!id) {
                state.currentType = state.expense[0];
            }

        })

        const choseType = (item) => {
            state.currentType = item;
            console.log(item);
        }

        const toggle = () => {
            state.show = !state.show;
        }

        const changeType = (type) => {
            state.payType = type;
            state.currentType = state[type][0]
        }

        const choseDay = (value) => {
            state.date = value;
            state.showDay = false;
        }

        const remove = () => {
            state.amount = state.amount.slice(0, state.amount.length - 1)
        }

        const inputChange = (value) => {
            if (value == '.' && state.amount.includes('.')) {
                return;
            }
            if (value != '.' && state.amount.includes('.') && state.amount.split('.')[1].length >= 2) {
                return;
            }
            state.amount += value;
        }

        const addBill = async () => {
            if (!state.amount) {
                Toast.fail('请输入具体金额')
                return
            }
            const params = {
                amount: Number(state.amount).toFixed(2),
                type_id: state.currentType.id,
                type_name: state.currentType.name,
                date: dayjs(state.date).unix() * 1000,
                pay_type: state.payType == 'expense' ? 1 : 2,
                remark: state.remark || '无备注'
            }

            if (id) {
                params.id = id;
                const result = await axios.post('/bill/update', params);
                state.show = false;
                Toast.success("修改成功")
                ctx.emit('refresh')
            } else {
                const result = await axios.post('/bill/add', params)
                state.amount = ''
                state.payType = 'expense'
                state.currentType = state.expense[0]
                state.show = false
                state.date = new Date()
                state.remark = ''
                Toast.success('添加成功')
                ctx.emit('refresh')
            }



        }
        return {
            ...toRefs(state),
            toggle,
            changeType,
            choseDay,
            remove,
            inputChange,
            choseType,
            addBill
        }
    }
}
</script>

<style lang="scss" scoped>
.add-wrap {
    padding-top: 12px;

    .header {
        display: flex;
        justify-content: space-between;
        padding: 0 24px;

        .van-icon-cross {
            font-size: 20px;
            color: $color-text-secondary;
        }

        .close {
            display: flex;
            align-items: center;
        }

        .add-btn {
            padding: 0 12px;
            background-color: $primary;
            border-color: $primary;
        }
    }

    .filter {
        padding: 12px 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .type {
            span {
                display: inline-block;
                background-color: #f5f5f5;
                color: $color-text-caption;
                padding: 4px 12px;
                font-size: 12px;
                border-radius: 24px;
                border: 1px solid #f5f5f5;
            }

            .expense {
                margin-left: 6px;

                &.active {
                    background-color: #eafbf6;
                    border-color: $primary;
                    color: $primary;
                }
            }

            .income {
                margin-left: 6px;

                &.active {
                    background-color: #fbf8f0;
                    border-color: $text-warning;
                    color: $text-warning;
                }
            }
        }

        .time {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 4px 12px;
            background-color: #f0f0f0;
            border-radius: 20px;
            color: $color-text-base;

            .icon-sort-down {
                font-size: 12px;
                margin-left: 5px;
                margin-bottom: 5px;
            }
        }

    }

    .money {
        padding-bottom: 12px;
        border-bottom: 1px solid #e9e9e9;
        margin: 0 24px;

        .sufix {
            font-size: 36px;
            font-weight: bold;
            vertical-align: top;
        }

        .amount {
            font-size: 40px;
            padding-left: 10px;
        }
    }

    .animation::after {
        content: '';
        display: inline-block;
        margin-left: 5px;
        width: 2px;
        height: 28px;
        animation: blink 1s infinite steps(1, start);
    }

    @keyframes blink {
        0% {
            background-color: white;
        }

        50% {
            background-color: $color-text-secondary;
        }

        100% {
            background-color: white;
        }
    }

    .van-number-keyboard {
        position: unset;
    }

    .type-wrap {
        display: flex;
        overflow-x: auto;
        margin: 0 24px;
        margin-bottom: 20px;

        * {
            touch-action: pan-x;
        }

        .type-body {
            display: flex;
            white-space: nowrap;

            .type-item {
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                padding: 16px 12px 10px 12px;

                .iconfont-wrap {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    background-color: #f5f5f5;
                    border-radius: 50%;
                    width: 30px;
                    height: 30px;
                    margin-bottom: 5px;

                    .iconfont {
                        color: $color-text-caption;
                        font-size: 20px;
                    }

                }

                .expense {
                    &.active {
                        background-color: $primary;

                        .iconfont {
                            color: #fff;
                        }
                    }
                }

                .income {
                    &.active {
                        background-color: $text-warning;

                        .iconfont {
                            color: #fff;
                        }
                    }
                }
            }
        }
    }

    .remark {
        padding: 0 24px;
        padding-bottom: 12px;
        color: #4b67e2;
    }
}
</style>